package collector

import (
	"fmt"

	"github.com/shirou/gopsutil/v3/mem"
	"sysinfo/internal/types"
	"sysinfo/internal/utils"
)

// CollectMemory 收集内存信息
func CollectMemory() (*types.MemoryData, error) {
	vmem, err := mem.VirtualMemory()
	if err != nil {
		return nil, fmt.Errorf("failed to get memory info: %w", err)
	}

	swap, err := mem.SwapMemory()
	if err != nil {
		// 交换区可能在所有系统上都不可用
		swap = &mem.SwapMemoryStat{}
	}

	data := &types.MemoryData{
		Total:          vmem.Total,
		Available:      vmem.Available,
		Used:           vmem.Used,
		UsedPercent:    vmem.UsedPercent,
		Free:           vmem.Free,
		TotalFormatted: utils.FormatBytes(vmem.Total),
		UsedFormatted:  utils.FormatBytes(vmem.Used),
		FreeFormatted:  utils.FormatBytes(vmem.Free),
		SwapTotal:      swap.Total,
		SwapUsed:       swap.Used,
		SwapFree:       swap.Free,
		SwapPercent:    swap.UsedPercent,
		Cached:         vmem.Cached,
		Buffers:        vmem.Buffers,
		Shared:         vmem.Shared,
	}

	// 尝试收集物理内存模块信息
	modules := collectMemoryModules()
	if len(modules) > 0 {
		data.Modules = modules
	}

	return data, nil
}

// collectMemoryModules 尝试收集物理RAM模块信息
// 这需要平台特定的实现或外部工具
func collectMemoryModules() []types.MemoryModule {
	// 如果可用，调用平台特定的实现
	return collectMemoryModulesPlatform()
}
